package ttot.channel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Destination {

	public static void main(String[] args) throws InterruptedException {
		Destination d = new Destination(8081);
		d.start();
	}

	private final int port;
	private final static int DEFAULT_PORT = 8080;

	public Destination(int port) {
		this.port = port;
	}

	public Destination() {
		this(DEFAULT_PORT);
	}

	private boolean stopped;
	private ServerSocket socket;
	private ExecutorService pool;

	public void start() {
		try {
			socket = new ServerSocket(port);
			pool = Executors.newFixedThreadPool(10);
			new Thread(new Runnable() {

				public void run() {
					while (!stopped) {
						try {
							System.out.println("Waiting for connection.");
							Socket cSocket = socket.accept();
							serve(cSocket);
						} catch (SocketException e) {
							if ("Socket closed".equals(e.getMessage())) {
								return;
							} else {
								throw new RuntimeException(e);
							}
						} catch (IOException e) {
							throw new RuntimeException(e);
						}
					}
				}

			}).start();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	private void serve(final Socket cSocket) {
		pool.submit(new Runnable() {
			public void run() {
				try {
					String line = new BufferedReader(new InputStreamReader(cSocket
							.getInputStream())).readLine();
					System.out.println(line);
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
		});
	}

	public void stop() {
		stopped = true;
		try {
			socket.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}